package com.uenpay.im.ui.old.activity.chat;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.adapter.QiYunXinAdapter;
import com.qyx.android.database.GroupTalkDbManager;
import com.qyx.android.database.SystemMsgManager;
import com.qyx.android.entity.SystemMsgEntity;
import com.qyx.android.message.type.MsgContentType;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.weight.json.JSONObject;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.group.GroupMangerHandler;
import com.uenpay.im.ui.old.activity.group.GroupType;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.RequestAcceptGroupEntity;
import com.uenpay.im.utilities.QyxDateUtils;
import com.uenpay.im.weight.MyDialog;
import com.uenpay.im.weight.RoundImageView;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.Date;

/**
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
public class TalkApplyFriendsListActivity extends BaseActivity {
    private ListView mListView;
    private View loading;
    private int index = 0;
    private GroupTalkDbManager mGroupTalkDbManager = new GroupTalkDbManager();
    private SystemMsgManager systemMsgManager = new SystemMsgManager();
    private long chat_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_list_layout;
    }

    @Override
    public void initView(View view) {
        mListView = (ListView) findViewById(R.id.listview);
        loading = findViewById(R.id.loading);
        chat_id = getIntent().getLongExtra("group_id", 0);
        ((TextView) findViewById(R.id.title_textview))
                .setText(R.string.audit_new_members);

        mListView.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                           int arg2, long arg3) {
                RequestAcceptGroupEntity entity = (RequestAcceptGroupEntity) arg0
                        .getAdapter().getItem(arg2);
                if (entity != null) {
                    deleteDialog(entity);
                }
                return true;
            }
        });

        getApply();
    }

    private void deleteDialog(final RequestAcceptGroupEntity user) {
        String[] delete_text = {IMApplication.getAppContext().getResources()
                .getString(R.string.delete_msg)};// �ı���Ϣ

        final MyDialog.Builder dlg = new MyDialog.Builder(this);
        final ListView menus = new ListView(this);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        menus.setLayoutParams(params);
        menus.setTag(delete_text);
        menus.setAdapter(new ArrayAdapter<String>(IMApplication
                .getAppContext(), R.layout.custom_contenxt_menu_item,
                delete_text));

        dlg.setListView(menus);
        dlg.setMessage("");
        if (!TextUtils.isEmpty(user.from_cust_name)) {
            dlg.setTitle(user.from_cust_name);
        } else {
            dlg.setTitle(R.string.action_dialog_title);
        }
        dlg.create().show();

        menus.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                switch (position) {
                    case 0:
                        deleteRequset(user.msg_no, Integer.valueOf(user.msg_type));
                        break;

                    default:
                        break;
                }
                dlg.getDialog().dismiss();
            }

        });

    }

    private void deleteRequset(String msg_no, int msg_type) {
        if (systemMsgManager.deleteSystemMsgByMsg(msg_no, msg_type)) {
            getApply();
        } else {
            IMApplication.showToast(getResources().getString(
                    R.string.delete_msg_failed));
        }

    }

    @Override
    public void onBackPressed() {
        finish();
        super.onBackPressed();
    }

    private void getApply() {
        ArrayList<RequestAcceptGroupEntity> entities = null;
        ArrayList<SystemMsgEntity> arraylist = systemMsgManager
                .querySystemMsgByMsgType(MsgContentType.APPLY_JOIN_GROUP_TALK);
        if (arraylist != null && arraylist.size() > 0) {
            entities = new ArrayList<RequestAcceptGroupEntity>();
            for (int i = 0, size = arraylist.size(); i < size; i++) {
                RequestAcceptGroupEntity requestEntity = new RequestAcceptGroupEntity();
                JSONObject json;
                try {
                    json = new JSONObject(arraylist.get(i).content_json);
                    requestEntity.notice_id = json.optInt("notice_id");
                    requestEntity.content = json.optString("content");
                    requestEntity.from_cust_name = json
                            .optString("from_cust_name");
                    requestEntity.from_cust_id = json.optString("from_cust_id");
                    requestEntity.msg_time = arraylist.get(i).msg_time;
                    requestEntity.msg_type = arraylist.get(i).msg_type;
                    requestEntity.msg_no = arraylist.get(i).msg_no;
                    entities.add(requestEntity);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }
        if (entities != null && entities.size() > 0) {
            ApplyNewFriends newFriends = new ApplyNewFriends(
                    TalkApplyFriendsListActivity.this, entities);
            mListView.setAdapter(newFriends);
        } else {
            myHandler.sendEmptyMessage(3);
        }
    }

    class ApplyNewFriends extends QiYunXinAdapter {

        LayoutInflater inflater;
        ArrayList<RequestAcceptGroupEntity> _requset;

        public ApplyNewFriends(Context mContext,
                               ArrayList<RequestAcceptGroupEntity> list) {
            inflater = LayoutInflater.from(mContext);
            _requset = list;
        }

        @Override
        public int getCount() {
            return _requset.size();
        }

        @Override
        public RequestAcceptGroupEntity getItem(int arg0) {
            return _requset.get(arg0);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(
                        R.layout.talk_apply_group_list_item, parent, false);
                holder.userName = (TextView) convertView
                        .findViewById(R.id.name_tv);
                holder.contentTv = (TextView) convertView
                        .findViewById(R.id.content_tv);
                holder.userIcon = (RoundImageView) convertView
                        .findViewById(R.id.avatar_iv);
                holder.addFriend = (Button) convertView
                        .findViewById(R.id.accept_btn);
                holder.request_time = (TextView) convertView
                        .findViewById(R.id.request_time);
                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final RequestAcceptGroupEntity requset = _requset.get(position);
            holder.userName.setText(requset.from_cust_name);// ������
            holder.contentTv.setText(requset.content);
            if (!TextUtils.isEmpty(requset.msg_time)) {
                holder.request_time.setText(QyxDateUtils
                        .generateDateTimeString(new Date(Long
                                .valueOf(requset.msg_time) * 1000)));
            }
            holder.userIcon.SetUrl(APIConfiguration.getAvatarUrlNormal(
                    requset.from_cust_id + "", PacketType.PERSONAL));
            holder.userIcon.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ActivityHandle.startUserDetailActivity(
                            TalkApplyFriendsListActivity.this,
                            requset.from_cust_id + "");
                }
            });

            holder.addFriend.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    loading.setVisibility(View.VISIBLE);
                    index = position;
                    acceptJoin(requset.notice_id + "", chat_id + "", 1,
                            requset.msg_no, requset.msg_type);
                }
            });

            return convertView;
        }

    }

    class ViewHolder {
        TextView userName, contentTv;
        RoundImageView userIcon;
        Button addFriend;
        TextView request_time;
    }

    /**
     * @param notice_id
     * @param chat_id
     */
    private void acceptJoin(String notice_id, final String chat_id, int accept,
                            final String msg_no, final int msg_type) {
        GroupMangerHandler.acceptJoinGroup(GroupType.NORMAL_GROUP, notice_id,
                accept, "", "", "", new GroupMangerHandler.IAcceptJoinGroupListener() {

                    @Override
                    public void onAcceptJoinGroupResult(int status, String msg) {
                        if (!TextUtils.isEmpty(msg)) {
                            IMApplication.showToast(msg);
                        }
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            Message message = myHandler.obtainMessage();
                            message.what = 1;
                            myHandler.sendMessage(message);
                            mGroupTalkDbManager.updateGroupNewMemberCount(
                                    Long.valueOf(chat_id), 0);
                            systemMsgManager.deleteSystemMsgByMsg(msg_no,
                                    msg_type);
                            getApply();
                        }
                    }
                });

        // AcceptJoinGroupInvokeItem acceptItem = new AcceptJoinGroupInvokeItem(
        // notice_id, accept);
        //
        // HttpRequestAsyncTaskQueue
        // .getInstance()
        // .AddTask(
        // new HttpTextAsyncTask(acceptItem)
        // .SetRequestType(HttpRequestType.SERVER_ONLY),
        // new OnHttpRequestTextListener() {
        //
        // @Override
        // public void OnSuccess(HttpInvokeItem item,
        // boolean isCache, String cacheFilePath) {
        // myHandler.sendEmptyMessage(2);
        //
        // AcceptJoinGroupInvokeItemResult result = ((AcceptJoinGroupInvokeItem)
        // item)
        // .getOutput();
        // if (result != null
        // && result.status == HttpInvokeResultCode.RESULT_OK) {
        // Message msg = myHandler.obtainMessage();
        // msg.what = 1;
        // myHandler.sendMessage(msg);
        // mGroupTalkDbManager
        // .updateGroupNewMemberCount(
        // Long.valueOf(chat_id), 0);
        // systemMsgManager.deleteSystemMsgByMsg(
        // msg_no, msg_type);
        // IMApplication.showToast(result.msg);
        // getApply();
        // } else {
        // if (isFinishing() || is_exit) {
        // return;
        // }
        // IMApplication.showToast(result.msg);
        // }
        // }
        //
        // @Override
        // public void OnProgress(long total_bytes,
        // long downloaded_bytes) {
        // }
        //
        // @Override
        // public void OnFail(boolean isCache, String reason) {
        // myHandler.sendEmptyMessage(2);
        // if (isFinishing() || is_exit) {
        // return;
        // }
        // IMApplication.showToast(reason);
        // }
        // });
    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                if (mListView != null) {
                    View view = null;
                    view = mListView.getChildAt(index);
                    if (view != null) {
                        ViewHolder holder = (ViewHolder) view.getTag();
                        if (holder != null) {
                            holder.addFriend.setVisibility(View.GONE);
                        }
                    }
                }
            } else if (msg.what == 2) {
                if (loading != null) {
                    loading.setVisibility(View.GONE);
                }
            } else if (msg.what == 3) {
                mListView.setVisibility(View.GONE);
                findViewById(R.id.no_data_tv).setVisibility(View.VISIBLE);
                ((TextView) findViewById(R.id.no_data_tv))
                        .setText(getResources().getString(R.string.not_apply));
            }
            return false;
        }
    });

}
